package com.sk.weichat.ui.me;

import android.content.Intent;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomSheetBehavior;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.sk.weichat.AppConstant;
import com.sk.weichat.MyApplication;
import com.sk.weichat.R;
import com.sk.weichat.adapter.MyCollectionAdapter;
import com.sk.weichat.audio_x.VoicePlayer;
import com.sk.weichat.bean.collection.Collectiion;
import com.sk.weichat.bean.collection.CollectionEvery;
import com.sk.weichat.downloader.Downloader;
import com.sk.weichat.helper.DialogHelper;
import com.sk.weichat.ui.base.BaseFragment;
import com.sk.weichat.ui.base.BaseLoginActivity;
import com.sk.weichat.ui.base.CoreManager;
import com.sk.weichat.ui.base.LazyFragment;
import com.sk.weichat.ui.mucfile.DownManager;
import com.sk.weichat.ui.mucfile.MucFileDetails;
import com.sk.weichat.ui.mucfile.XfileUtils;
import com.sk.weichat.ui.mucfile.bean.DownBean;
import com.sk.weichat.ui.mucfile.bean.MucFileBean;
import com.sk.weichat.ui.tool.SingleImagePreviewActivity;
import com.sk.weichat.util.ToastUtil;
import com.sk.weichat.video.ChatVideoPreviewActivity;
import com.sk.weichat.view.SelectionFrame;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.callback.ListCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ArrayResult;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

import static com.sk.weichat.ui.mucfile.DownManager.STATE_DOWNLOADED;

public class CollectionFragment extends BaseFragment {
    private static final int maxDeleteCount = 20;
    private SmartRefreshLayout refreshLayout;
    private RecyclerView recyclerView;

    public List<CollectionEvery> getData() {
        return data;
    }

    private List<CollectionEvery> data = new ArrayList<>();
    public LinearLayout ll_layout_search_empty;
    private ImageView image_empty;
    private TextView tv_empty;
    private boolean isItemDeleteAble;
    private boolean isItemEditAble;

    private LoadListener listener;

    public boolean isSelectAble() {
        return isSelectAble;
    }

    public void setSelectAble(boolean selectAble) {
        isSelectAble = selectAble;
        if (myCollectionAdapter != null) {
            List<CollectionEvery> list = myCollectionAdapter.getData();
            for (int i = 0; i < list.size(); i++) {
                list.get(i).isEdit = selectAble;
            }
            if (myCollectionAdapter != null) {
                myCollectionAdapter.notifyDataSetChanged();
            }
        }
    }

    public void notifiDataSetChange() {
        if (myCollectionAdapter != null) {
            myCollectionAdapter.notifyDataSetChanged();
        }
    }

    private boolean isSelectAble = false;

    private MyCollectionAdapter myCollectionAdapter;

    private void intentPreviewFile(String url, String fileName, String fromName, long size) {
        MucFileBean data = new MucFileBean();
        fileName = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
        // 取出文件后缀
        int start = url.lastIndexOf(".");
        String suffix = start > -1 ? url.substring(start + 1).toLowerCase() : "";

        int fileType = XfileUtils.getFileType(suffix);
        data.setNickname(fromName);
        data.setUrl(url);
        data.setName(fileName);
        data.setSize(size);

        data.setType(fileType);

        Intent intent;
        File file2 = new File(DownManager.instance().getFileDir() + File.separator + fileName);
        data.setFilePath(file2.getAbsolutePath());

        if (file2.exists()) {
            DownBean downBean = DownManager.instance().getDownloadState(data);
            data.setState(downBean.state);
        }
        if (data.getState() == STATE_DOWNLOADED && (data.getType() == 2 || data.getType() == 3)) {
            intent = new Intent(getActivity(), ChatVideoPreviewActivity.class);
            intent.putExtra(AppConstant.EXTRA_VIDEO_FILE_PATH, file2.getAbsolutePath());
        } else {
            intent = new Intent(getActivity(), MucFileDetails.class);
            intent.putExtra("data", data);
        }

        //intent.putExtra("data", data);
        getActivity().startActivity(intent);
    }

    private void adjustEmpty() {
        if (myCollectionAdapter.getData().size() > 0) {
            recyclerView.setVisibility(View.VISIBLE);
            ll_layout_search_empty.setVisibility(View.GONE);
        } else {
            recyclerView.setVisibility(View.GONE);
            ll_layout_search_empty.setVisibility(View.VISIBLE);
        }
    }

    public void getMyCollectionList() {
        Map<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("userId", coreManager.getSelf().getUserId());
        HttpUtils.get().url(coreManager.getConfig().Collection_LIST_OTHER)
                .params(params)
                .build()
                .execute(new ListCallback<CollectionEvery>(CollectionEvery.class) {
                    @Override
                    public void onResponse(ArrayResult<CollectionEvery> result) {
                        if (result.getResultCode() == 1 && result.getData() != null) {

                            List<CollectionEvery> list = result.getData();
                            for (int i = 0; i < list.size(); i++) {
                                list.get(i).deleteAble = isItemDeleteAble;
                                list.get(i).isEdit = isItemEditAble;
                            }
                            data.clear();
                            data.addAll(list);
                            //myCollectionAdapter.setNewData(result.getData());
                            myCollectionAdapter.notifyDataSetChanged();
                            refreshLayout.finishRefresh();
                            adjustEmpty();
                            if (listener != null) {
                                listener.onLoadFinish();
                            }
                        } else {
                            ll_layout_search_empty.setVisibility(View.VISIBLE);
                            refreshLayout.finishRefresh();
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        ToastUtil.showErrorNet(getActivity());
                        refreshLayout.finishRefresh();
                    }
                });
    }

    @Override
    protected void initView() {
        Downloader.getInstance().init(MyApplication.getInstance().mAppDir + File.separator + coreManager.getSelf().getUserId()
                + File.separator + Environment.DIRECTORY_MUSIC);

        isItemDeleteAble = getArguments() != null ? getArguments().getBoolean("isItemDeleteAble") : false;
        isItemEditAble = getArguments() != null ? getArguments().getBoolean("isItemEditAble") : false;

        ll_layout_search_empty = findViewById(R.id.ll_layout_search_empty);
        image_empty = findViewById(R.id.image_empty);
        tv_empty = findViewById(R.id.tv_empty);
        image_empty.setImageResource(R.mipmap.img05_relationship);
        tv_empty.setText(getActivity().getString(R.string.tips_collection_emty));


        recyclerView = findViewById(R.id.recyclerview);
        refreshLayout = findViewById(R.id.refreshLayout);
        // refreshLayout.setDragRate(0.4f);//刷新拉动阻尼效果，数值越小，拉动距离越大
        refreshLayout.setEnableOverScrollBounce(false);//禁止越界回弹
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                getMyCollectionList();
            }
        });
        myCollectionAdapter = new MyCollectionAdapter(data);
        myCollectionAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (!isSelectAble) {
                    return;
                }
                List<CollectionEvery> list = myCollectionAdapter.getData();
                CollectionEvery item = list.get(position);
                int count = 0;
                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i).isChecked) {
                        count++;
                    }
                }
                //最多只能选择20个
                if (count >= maxDeleteCount && !item.isChecked) {
                    return;
                }
                if (isItemEditAble) {
                    if (count == 0) {//选中
                        ((SelectCollectionActivity) getActivity()).sendable(true);
                    } else if (count == 1 && item.isChecked) {//未选中
                        ((SelectCollectionActivity) getActivity()).sendable(false);
                    }
                }
                item.isChecked = !item.isChecked;
                myCollectionAdapter.notifyDataSetChanged();
            }
        });


        myCollectionAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                CollectionEvery item = myCollectionAdapter.getData().get(position);
                switch (view.getId()) {
                    case R.id.iv_avatar:
                    case R.id.tv_name:
                        Intent intent = new Intent(getActivity(), PersonalCenterActivity.class);
                        intent.putExtra(AppConstant.EXTRA_USER_ID, item.getFromUserId() + "");
                        getActivity().startActivity(intent);
                        break;
                    case R.id.tv_delete:
                        showDeleteMsgDialog(new SelectionFrame.OnSelectionFrameClickListener() {

                            @Override
                            public void cancelClick() {

                            }

                            @Override
                            public void confirmClick() {
                                deleteCollection(item);
                            }
                        });
                        break;
                    case R.id.iv_check:
                        List<CollectionEvery> list = myCollectionAdapter.getData();
                        int count = 0;
                        for (int i = 0; i < list.size(); i++) {
                            if (list.get(i).isChecked) {
                                count++;
                            }
                        }
                        //最多只能选择20个
                        if (count >= maxDeleteCount && !item.isChecked) {
                            String toastMsg = "";
                            if (isItemEditAble) {
                                toastMsg = getString(R.string.tips_max_colloction_for_select);
                            } else {
                                toastMsg = getString(R.string.tips_max_colloction_for_delete);
                            }
                            ToastUtil.showToast(getActivity(), toastMsg);
                            return;
                        }
                        if (isItemEditAble) {
                            if (count == 0) {//选中
                                ((SelectCollectionActivity) getActivity()).sendable(true);
                            } else if (count == 1 && item.isChecked) {//未选中
                                ((SelectCollectionActivity) getActivity()).sendable(false);
                            }
                        }
                        item.isChecked = !item.isChecked;
                        myCollectionAdapter.notifyDataSetChanged();
                        break;

                    case R.id.iv_image:
                        ImagePreviewActivity.startImagePreviewActivity(getActivity(), item.getUrl());
                        break;
                    case R.id.tv_bg:
                    case R.id.iv_doc_type_icon:
                    case R.id.tv_doc_name:
                    case R.id.tv_doc_size:
                        String fileName = item.getFileName();
                        String suffix = "";
                        try {
                            suffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
                        } catch (Exception e) {

                        }
                        if (suffix.equals("jpg") || suffix.equals("jpeg") || suffix.equals("png")) {
                            ImagePreviewActivity.startImagePreviewActivity(getActivity(), item.getUrl());
                        } else {
                            intentPreviewFile(item.getUrl(), item.getFileName(), item.getName(), item.getFileSize());
                        }
                        break;
                    case R.id.view_mask:
                        Intent intent2 = new Intent(getActivity(), ChatVideoPreviewActivity.class);
                        //判断本地文件是否存在
                        String name = item.getFileName().substring(item.getFileName().lastIndexOf("/") + 1);
                        File file = new File(DownManager.instance().getFileDir() + File.separator + name);
                        if (file.exists()) {
                            intent2.putExtra(AppConstant.EXTRA_VIDEO_FILE_PATH, file.getAbsolutePath());
                        } else {
                            intent2.putExtra(AppConstant.EXTRA_VIDEO_FILE_PATH, item.getUrl());
                        }
                        startActivity(intent2);
                        break;
                }
            }
        });

        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.setAdapter(myCollectionAdapter);

        refreshLayout.autoRefresh();
    }

    @Override
    public void onStop() {
        VoicePlayer.instance().stop();
        super.onStop();
    }

    private void showDeleteMsgDialog(SelectionFrame.OnSelectionFrameClickListener onSelectionFrameClickListener) {
        SelectionFrame dialog = new SelectionFrame(getActivity());
        dialog.setSomething(null, getActivity().getString(R.string.delete_prompt), onSelectionFrameClickListener);
        dialog.show();
    }


    public void deleteCollection(CollectionEvery collectionEvery) {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("emojiId", collectionEvery.getEmojiId());

        HttpUtils.get().url(CoreManager.requireConfig(MyApplication.getInstance()).Collection_REMOVE)
                .params(params)
                .build()
                .execute(new BaseCallback<Collectiion>(Collectiion.class) {
                    @Override
                    public void onResponse(ObjectResult<Collectiion> result) {
                        if (result.getResultCode() == 1) {
                            if (collectionEvery.getType() == CollectionEvery.TYPE_VOICE) {
                                //删除语音，停止播放
                                VoicePlayer.instance().stop();
                            }
                            myCollectionAdapter.getData().remove(collectionEvery);
                            myCollectionAdapter.notifyDataSetChanged();
                            adjustEmpty();
                            if (listener != null) {
                                listener.onLoadFinish();
                            }
                        } else {

                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        DialogHelper.dismissProgressDialog();
                        ToastUtil.showErrorNet(getActivity());
                    }
                });
    }

    @Override
    public void onDestroy() {
        Log.e("lzs", "onDestroy");
        super.onDestroy();
    }

    @Override
    public void loadingData() {

    }

    @Override
    protected int inflateLayoutId() {
        return R.layout.fragment_my_collection;
    }

    public void setListener(LoadListener listener) {
        this.listener = listener;
    }

    public interface LoadListener {
        void onLoading();

        void onLoadFinish();
    }


}
